﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.WindowsAzure.ServiceManagement;

namespace WAPA.Framework
{
    public class SendCalculationTasksAction :IAction
    {
        public int NoMillionDigits;
        public DeploymentList Deployments;
        public string QueueName = null;
        public int RepeatCount;
        public int RepeatInterval;

        public SendCalculationTasksAction()
        {
            NoMillionDigits = 10;
            RepeatCount = 1;
            RepeatInterval = 0;
        }

        public void Execute()
        {
            DeploymentList deploymentList = CloudServiceManager.GetDeployments();

            //We have to lookup the servicename of the deployments. For this we need up-to-date detail info on the hosted services.
            HostedServiceList hostedServices = CloudServiceManager.GetHostedServicesWithDetails();

            foreach (Deployment deployment in deploymentList)
            {
                foreach (HostedService hostedService in hostedServices)
                {
                    var lookup = from n in hostedService.Deployments where n.PrivateID == deployment.PrivateID select n;

                    if (lookup.Count() == 1)
                    {
                        QueueName = hostedService.ServiceName;
                        break;
                    }
                }

                if (QueueName == null) continue;

                //Since we're using queue we don't have to wait for the deployments to get ready.
                if (deployment.RoleInstanceList.Count > 0)
                {
                    CalculatePiTaskMessage workerTaskMessage = new CalculatePiTaskMessage();
                    workerTaskMessage.NoMillionDigits = NoMillionDigits;
                    workerTaskMessage.StorageAccessKey = ManagementContext.AccessKey;
                    workerTaskMessage.StorageAccountName = ManagementContext.StorageAccountName;
                    workerTaskMessage.StorageBlobEndPointUrl = ManagementContext.BlobEndpointUri;
                    workerTaskMessage.TaskId = Guid.NewGuid().ToString();
                    workerTaskMessage.DeploymentId = deployment.PrivateID;
                    workerTaskMessage.OutputContainerName = ManagementContext.OutputContainerName;
                    workerTaskMessage.Splitted = false;
                    workerTaskMessage.SplittedStateBlob = "";
                    workerTaskMessage.SplitCommandArguments = "";
                    workerTaskMessage.RepeatCount = RepeatCount;
                    workerTaskMessage.RepeatInterval = RepeatInterval;//Seconds

                    CloudServiceManager.SendQueueMessage(QueueName, MessageSerializer.Serialize(workerTaskMessage));
                }
            }
        }
    }
}
